<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2018/4/14
 * Time: 10:54
 */

namespace App\Http\Utils;

use Illuminate\Support\Facades\Redis;

class TokenUtils
{
    const ERROR_MESSAGE_NO_TOKEN = 'token不能为空';
    const ERROR_MESSAGE_TOKEN_ERROR = 'token错误';

    const TOKEN_NAME    = 'token';      // token的key
    const TOKEN_LIFETIME=  604800;      // Token的保存时间   7 天


    /**
     * 获取Token
     * @return string
     */
    public static function T()
    {
        return request(self::TOKEN_NAME, '');
    }

    /**
     * 保存用户信息在Memcache中
     * @param $userData     @用户数据
     * @param $token        @用户Token
     * @return mixed        @null, 没保存成功， token，凭证
     */
    public static function S($userData, $token = '')
    {
        // 没有token,创建Token
        if (empty($token)) $token = self::_createToken($userData);

        $result = Redis::setex('user:'.$token,self::TOKEN_LIFETIME,  json_encode($userData));
        if ($result == false) return null;
        return $token;
    }

    /**
     * 清楚用户数据
     * @return mixed
     */
    public static function C()
    {
        $key = 'user:' . self::T();
        if (Redis::exists($key)) {

            if (Redis::del($key)) return JUtil::S();
        }
        return JUtil::E(self::ERROR_MESSAGE_TOKEN_ERROR);
    }

    /**
     * 创建TOKEN
     * @param $userData                 @用户数据
     * @return string                   @返回Token
     */
    private static function _createToken($userData)
    {
        $userData = json_encode($userData);
        return md5(md5($userData.uniqid()));
    }



}